
package com.epam.android.training.level1.db.rss;

import com.epam.android.training.level1.db.rss.Rss.Category;
import com.epam.android.training.level1.db.rss.Rss.Feed;
import com.epam.android.training.level1.db.rss.Rss.Item;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Anton Novikau
 */
public class RssDbHelper extends SQLiteOpenHelper {

  private static final String TAG = RssDbHelper.class.getSimpleName();

  private static final String DB_NAME = "rss.db";

  private static final int DB_VERSION = 1;

  /**
   * Creates an instance of RssDbHelper.
   * 
   * @param context
   */
  public RssDbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    StringBuilder queryBuilder = new StringBuilder();
    // create Feed table
    queryBuilder.append("CREATE TABLE ").append(Feed.TABLE_NAME).append(" (").append(Feed._ID)
        .append(" INTEGER PRIMARY KEY,").append(Feed.TITLE).append(" TEXT NOT NULL,")
        .append(Feed.FEED_URL).append(" TEXT UNIQUE NOT NULL,").append(Feed.LINK)
        .append(" TEXT NOT NULL,").append(Feed.ICON).append(" BLOB);");
    db.execSQL(queryBuilder.toString());
    queryBuilder.setLength(0);

    // create Feed Item table
    queryBuilder.append("CREATE TABLE ").append(Item.TABLE_NAME).append(" (").append(Item._ID)
        .append(" INTEGER PRIMARY KEY,").append(Item.FEED_ID).append(" INTEGER,")
        .append(Item.TITLE).append(" TEXT NOT NULL,").append(Item.LINK).append(" TEXT NOT NULL,")
        .append(Item.DESC).append(" TEXT,").append(Item.PUB_DATE).append(" INTEGER NOT NULL,")
        .append(Item.IS_READ).append(" INTEGER DEFAULT 0,").append("FOREIGN KEY(")
        .append(Item.FEED_ID).append(") REFERENCES ").append(Feed.TABLE_NAME).append("(")
        .append(Feed._ID).append("));");
    db.execSQL(queryBuilder.toString());
    queryBuilder.setLength(0);

    // create Feed Category table
    queryBuilder.append("CREATE TABLE ").append(Category.TABLE_NAME).append(" (")
        .append(Category._ID).append(" INTEGER PRIMARY KEY,").append(Category.FEED_ID)
        .append(" INTEGER,").append(Category.NAME).append(" TEXT NOT NULL,").append("FOREIGN KEY(")
        .append(Category.FEED_ID).append(") REFERENCES ").append(Feed.TABLE_NAME).append("(")
        .append(Feed._ID).append("));");
    ;
    db.execSQL(queryBuilder.toString());
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
        + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + Feed.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + Item.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + Category.TABLE_NAME);
    onCreate(db);
  }
}
